<?php if(!defined('PUBLIC_DIR')) die('No Access!');
using('System.Data');
using('System.Web');

Cnamespace('System.Web');
class Uri implements iUri{
	private static $DBHandler = NULL;
	private static $DefaultConditions;
	private $Name;
	private $Pattern;
	private $Conditions;

	public function __construct($_name, $_pattern = null, array $_conditions = null){
		if(!is_null($_pattern) && is_string($_pattern)){
			$this->Name = $_name;
			$this->Pattern = $_pattern;
			$this->Conditions = $_conditions;
		}else{
			if (self::$DBHandler == NULL)
				self::$DBHandler = Config::GetProvider();
			self::$DBHandler->Query("SELECT pattern, conditions FROM [Traces] WHERE name = '$_name' LIMIT 1;");
			$uri = self::$DBHandler->FetchArray();
			$this->Name = $_name;
			$this->Pattern = $uri['pattern'];
			$this->Conditions = (array)unserialize($uri['conditions']);
		}
	}
	public static function SetDefaultConditions(array $_defaultConditions){
		self::$DefaultConditions = $_defaultConditions;
	}
	public static function GetDefaultConditions(){
		return self::$DefaultConditions;
	}
	public function GetName(){
		return $this->Name;
	}
	public function GetPattern(){
		return $this->Pattern;
	}
	public function GetConditions(){
		return $this->Conditions;
	}
	public function CreateUrl($_params){
	}
	public function CreateRegex(){
		$patternAsRegex = preg_replace_callback('@:[\w]+@', array($this, 'ConvertPatternToRegex'), $this->Pattern);
		if (substr($this->Pattern, -1) === '/'){
			$patternAsRegex = $patternAsRegex . '?';
		}
		return $patternAsRegex = '@^' . $patternAsRegex . '$@';
	}
	private function ConvertPatternToRegex($_matches){
		$key = str_replace(':', '', $_matches[0]);
		if(array_key_exists($key, $this->Conditions)){
			return '(?P<' . $key . '>' . $this->Conditions[$key] . ')';
		}else if(array_key_exists('*', $this->Conditions)){
			return '(?P<' . $key . '>' . $this->Conditions['*'] . ')';
		}else{
			return '(?P<' . $key . '>[a-zA-Z0-9_\-\.\!\~\*\\\'\(\)\:\@\&\=\$\+\,\%]+)';
		}
	}
}
